package cn.fengshenghospital.controller;

import cn.fengshenghospital.entity.Article;
import cn.fengshenghospital.entity.Logs;
import cn.fengshenghospital.entity.User;
import cn.fengshenghospital.service.ArticleService;
import cn.fengshenghospital.utils.Constants;
import cn.fengshenghospital.vo.JsonBean;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.java2d.pipe.AATextRenderer;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

//@RestController
@Controller
@RequestMapping("/article")
public class ArticleController {
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    @Autowired
    private ArticleService articleService;
    //根据菜单ID查询文章
    @RequestMapping("/queryArticleByMid")
    @ResponseBody
    public JsonBean queryArticleByMid(Integer mid,Integer pageIndex){
        JsonBean jsonBean=new JsonBean("queryArticleByMid");
        try {
            List<Article> articleList=articleService.getArticleByMid(mid,pageIndex, Constants.PageSize);
            int totalPage=articleService.getArticleCount(mid);
            Map map=new HashMap();
            map.put("datalist",articleList);
            map.put("totalPage",totalPage%Constants.PageSize==0?totalPage/Constants.PageSize:(totalPage/Constants.PageSize)+1);
            map.put("pageIndex",pageIndex);
            jsonBean.setStatus(200);
            jsonBean.setData(map);
        } catch (Exception e) {
            e.printStackTrace();
            jsonBean.setData(-1);
        }
        return jsonBean;
    }
    @GetMapping("/test")
    public String test(){
        return "addArticle";
    }
    //搜索文章
    @RequestMapping("/searchArticle")
    @ResponseBody
    public JsonBean searchArticle(@RequestParam Map<String,Object> conditionMap){
        JsonBean jsonBean=new JsonBean("searchArticle");
        Integer pageIndex = Integer.parseInt(conditionMap.get("pageIndex").toString());
        conditionMap.put("startSize",(pageIndex-1)*Constants.PageSize);
        conditionMap.put("endSize",Constants.PageSize);
        try {
            Map map=new HashMap();
            List<Article> articleList=articleService.searchArticle(conditionMap);
            int totalPage=articleService.searchArticleCount(conditionMap);
            map.put("dataList",articleList);
            map.put("totalPage",totalPage%Constants.PageSize==0?totalPage/Constants.PageSize:(totalPage/Constants.PageSize)+1);
            map.put("pageIndex",pageIndex);
            jsonBean.setStatus(200);
            jsonBean.setData(map);
        } catch (Exception e) {
            e.printStackTrace();
            jsonBean.setData(-1);
        }
        return jsonBean;
    }

    //搜索文章
    @RequestMapping("/queryArticleInfo")
    @ResponseBody
    public JsonBean  queryArticleInfo(Integer aid){
        JsonBean jsonBean=new JsonBean("queryArticleInfo");
        try {
            Article article=articleService.getArticleById(aid);
            jsonBean.setData(article);
            jsonBean.setStatus(200);
        } catch (Exception e) {
            e.printStackTrace();
            jsonBean.setData(-1);
        }
        return jsonBean;
    }
    //插入文章
    @RequestMapping("/addArticle")
    public String addArticle(String articleTitle,String context){
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        System.out.println(user.getUid());
        Article article = new Article();
        article.setArticletitle(articleTitle);
        article.setCreateBy(user.getUid());
        article.setContext(context);
        Logs logs = new Logs();
        logs.setUserName("test");
        logs.setDate("test");
        logs.setDes("添加文章");
        logs.setUid(user.getUid());
        logs.setMenu("文章");
//        upImg(file,request);
        try{
            articleService.addArticleById(article,logs);
        }catch (Exception e){
            e.printStackTrace();
        }

        return "articletitle";
    }
    @RequestMapping("/testUpImg")
    public String testUpImg(){
        return "testFileImg";
    }

    public String upImg(@RequestParam("img") MultipartFile file, HttpServletRequest request){
        if (file.isEmpty()) {
            return new String("文件为空");
        }
// 获取文件名
        String fileName = file.getOriginalFilename();
        logger.info("上传的文件名为：" + fileName);
// 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        logger.info("上传的后缀名为：" + suffixName);
        if(".jpg".equals(suffixName.trim())||".png".equals(suffixName.trim())){

            // 文件上传后的路径
            String filePath = request.getContextPath()+"/";//服务器路径
            System.out.println(filePath);
// 解决中文问题，liunx下中文路径，图片显示问题
// fileName = UUID.randomUUID() + suffixName;
            fileName=  UUID.randomUUID().toString().replace("-", "")+".png";
            File dest = new File(filePath +fileName);
// 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();

            }
            try {
                file.transferTo(dest);

            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new String("上传的不是图片！");
    }


    //查询文章
    @RequestMapping("/queryContext")
    public String queryContext(Model model){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("page",1);
        map.put("pageSize",Constants.PageSize);
        int totalPage = articleService.queryArticleCount(map);
        List<Article> articleList = articleService.queryArticle(map);
        model.addAttribute("articleList",articleList);
        model.addAttribute("totalPage",totalPage);
        return "articletitle";
    }

    //多条件分页搜索
    @RequestMapping("/queryArticleByTiaoJian")
    @ResponseBody
    public JsonBean<List<Article>> queryArticleByTiaoJian(String articleTitle,int page){
        JsonBean<List<Article>> jsonBean = new JsonBean<>("queryArticleByTiaoJian");
        jsonBean.setStatus(200);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("articleTitle",articleTitle);
        map.put("page",page);
        map.put("pageSize",Constants.PageSize);
        List<Article> list = articleService.queryArticle(map);
        jsonBean.setData(list);
        return jsonBean;
    }
    @RequestMapping("/toUpdateArticle")
    //去修改文章页
    public String toUpdateArticle(Model model,int aid){
        Map<String,Object> map = new HashMap<>();
        map.put("articleId",aid);
        List<Article> articleList = articleService.queryArticle(map);
        Article article = articleList.get(0);
        model.addAttribute("article",article);
        model.addAttribute("cmd","updateArticle");
        return "addArticle";
    }
    //跳转添加文章页
    @RequestMapping("/toAddArticle")
    public String toAddArticle(){
        return "addArticle";
    }
    @RequestMapping("/updateArticle")
    @ResponseBody
    //修改文章
    public String updateArticle(int articleId,String articleTitle,String context){
        System.out.println("a");
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        Article article = new Article();
        article.setArticleId(articleId);
        article.setArticletitle(articleTitle);
        article.setModifyBy(1);
        article.setContext(context);
        Logs logs = new Logs();
        logs.setUserName("test");
        logs.setDate("test");
        logs.setDes("修改文章");
        logs.setUid(1);
        logs.setMenu("文章");
        try {
            articleService.updateArticle(article,logs);
        }catch (Exception e){
            e.printStackTrace();
        }

        return "articletitle";
    }

}
